﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Communications;

using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Event
{
    public partial class EventNav : CGOBase, IModuleCommunicator
    {
        public event ModuleCommunicationEventHandler ModuleCommunication;
        protected int eventID = 0;
        public const string COMM_TEXT = "EventID";
        public const string COMM_TYPE = "EventSelectChange";

        public int CharityID
        {
            get
            {
                if ((Request.QueryString["CharityID"] != null))
                {
                    return Int32.Parse(Request.QueryString["CharityID"]);
                }
                else
                    return 0;
            }
        }

        public int EventID
        {
            get
            {
                if (eventID == 0)
                {
                    if ((Request.QueryString["EventID"] != null))
                    {
                        eventID = Int32.Parse(Request.QueryString["EventID"]);
                    }
                }
                return eventID;
            }
        }


        public bool boolViewArchive
        {
            get
            {
                if (!Null.IsNull(Settings["ShowArchive"]))
                {
                    return Boolean.Parse(Settings["ShowArchive"].ToString());
                }
                else
                    return false;
            }
        }

        public string EventNameFormat
        {
            get
            {
                return "{0}...";
                //return Localization.GetString("CharityNameFormat", LocalResourceFile);
            }
        }

        #region Event Handler
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {                
                //if page is first load, check charity id url parameter first, if there is, use it
                //if not bind data directly, EventID will be assigned with the id of the first charity in return list
                //if no event return, EventID remains the null value, -1
                //at last, if partial render is enabled, send communication to other module, if not, use redirect to nav
                if (!Page.IsPostBack)
                {
                    BindData();
                }
            }

            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected override void EnsureChildControls()
        {
            if (ModuleConfiguration.ModuleControl.SupportsPartialRendering && !Page.IsPostBack)
            {
                CommunicationSend(COMM_TYPE, COMM_TEXT, EventID.ToString());
            }
            base.EnsureChildControls();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dlEvent_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dlEvent_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            LinkButton btnEventLink = e.Item.FindControl("btnEventLink") as LinkButton;
            HyperLink lnkEvent = e.Item.FindControl("lnkEvent") as HyperLink;

            if (btnEventLink != null)
                btnEventLink.Visible = ModuleConfiguration.ModuleControl.SupportsPartialRendering ;

            if (lnkEvent != null)
                lnkEvent.Visible = !ModuleConfiguration.ModuleControl.SupportsPartialRendering;

            if (ModuleConfiguration.ModuleControl.SupportsPartialRendering)
            {
                if (btnEventLink != null)
                {
                    btnEventLink.Click += new EventHandler(btnEventLink_Click);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEventLink_Click(object sender, EventArgs e)
        {
            LinkButton btnEventLink = sender as LinkButton;
            if (btnEventLink != null)
            {
                try
                {
                    CommunicationSend(COMM_TYPE, COMM_TEXT, btnEventLink.CommandArgument);
                    eventID = Int32.Parse(btnEventLink.CommandArgument);
                    BindData();
                }
                catch (Exception exc) //Module failed to load
                {
                    Exceptions.ProcessModuleLoadException(this, exc);
                }
            }
        }
        #endregion

        #region Private Funtions

        private void BindData()
        {
            EventController ctrlEvent = new EventController();
            List<EventInfo> lstEvent;

            if (boolViewArchive)
            {
                DateTime beginDate = DateTime.Now.Date.AddYears(-1);
                lstEvent = ctrlEvent.GetEvents(PortalId, CharityID, Null.NullDate, DateTime.Now.Date);
            }
            else
            {
                lstEvent = ctrlEvent.GetEvents(PortalId, CharityID, DateTime.Now.Date, Null.NullDate);
            }

            if (EventID==0)
            {
                if (lstEvent.Count > 0)
                {
                    eventID = lstEvent[0].EventID;
                    Response.Redirect(Globals.NavigateURL(TabId, string.Empty, "EventID=" + eventID.ToString()), true);
                }
                dlEvent.SelectedIndex = 0;
            }
            else
            {
                for (int i = 0; i < lstEvent.Count; i++)
                {
                    if (lstEvent[i].EventID == EventID)
                    {
                        dlEvent.SelectedIndex = i;
                        break;
                    }
                }
            }

            dlEvent.DataSource = lstEvent;
            dlEvent.DataBind();
        }

        private void CommunicationSend(string Type, string Text, string Value)
        {
            ModuleCommunicationEventArgs MCArgs = new ModuleCommunicationEventArgs();
            MCArgs.Sender = "CharityGamesOnline.Modules.Event.EventNav";
            MCArgs.Type = Type;
            MCArgs.Target = string.Empty;
            MCArgs.Text = Text;
            MCArgs.Value = Value;

            if (ModuleCommunication != null)
            {
                ModuleCommunication(this, MCArgs);
            }
        }
        #endregion
    }
}